package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ReportServiceImpl implements ReportService {
    private final OrderMapper orderMapper;
    private final UserMapper userMapper;
    private final WorkspaceService workspaceService;

    @Autowired
    public ReportServiceImpl(OrderMapper orderMapper, UserMapper userMapper, WorkspaceService workspaceService) {
        this.orderMapper = orderMapper;
        this.userMapper = userMapper;
        this.workspaceService = workspaceService;
    }


    /**
     * 营业额统计接口
     *
     * @param begin 开始日期
     * @param end   结束日期
     * @return vo
     */
    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        //存放开始日期到结束日期之间的日期
        List<LocalDate> dateList = generateDateList(begin, end);
        //存放每天的营业额
        List<Double> turnovers = new ArrayList<>();
        //查询date日期对应的营业额数据，营业额：状态为 已完成 的订单金额累加
        for (LocalDate date : dateList) {
            Map<String, Object> map = new HashMap<>();
            map.put("begin", fromMinDate(date));
            map.put("end", fromMaxDate(date));
            map.put("status", Orders.COMPLETED);
            Double turnover = orderMapper.sumByMap(map);
            turnovers.add(turnover == null ? 0.0 : turnover);
        }

        return TurnoverReportVO.builder().dateList(StringUtils.join(dateList, ",")).turnoverList(StringUtils.join(turnovers, ",")).build();
    }

    /**
     * 订单统计接口
     *
     * @param begin 开始日期
     * @param end   结束日期
     * @return vo
     */
    @Override
    public OrderReportVO getOrdersStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = generateDateList(begin, end);
        //每日订单数
        List<Integer> orderCountList = new ArrayList<>();
        List<Integer> validOrderCountList = new ArrayList<>();
        for (LocalDate date : dateList) {
            Map<String, Object> map = new HashMap<>();
            map.put("begin", fromMinDate(date));
            map.put("end", fromMaxDate(date));
            Integer dayCount = orderMapper.countByMap(map); //每日的订单总数
            orderCountList.add(dayCount == null ? 0 : dayCount);
            map.put("status", Orders.COMPLETED);
            Integer validOrderCount = orderMapper.countByMap(map); //每日的有效订单数
            validOrderCountList.add(validOrderCount == null ? 0 : validOrderCount);
        }
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).orElse(0); //订单总数
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).orElse(0); //有效订单数
        Double orderCompletionRate = totalOrderCount > 0 ? (double) validOrderCount / totalOrderCount : 0; //订单完成率

        DecimalFormat df = new DecimalFormat("#.00");
        String formattedNumber = df.format(orderCompletionRate);
        //返回数据
        return OrderReportVO.builder().dateList(StringUtils.join(dateList, ",")).orderCountList(StringUtils.join(orderCountList, ",")).validOrderCountList(StringUtils.join(validOrderCountList, ",")).totalOrderCount(totalOrderCount).validOrderCount(validOrderCount).orderCompletionRate(Double.parseDouble(formattedNumber)).build();
    }

    /**
     * 用户统计接口
     *
     * @param begin 开始时间
     * @param end   结束时间
     * @return vo
     */
    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = generateDateList(begin, end);
        List<Integer> totalUserList = new ArrayList<>(); //每天总用户数量
        List<Integer> newUserList = new ArrayList<>();//每天新增用户数量
        for (LocalDate date : dateList) {
            Map<String, Object> map = new HashMap<>();
            map.put("end", fromMaxDate(date));
            Integer totalCount = userMapper.countByTime(map); //每天用户总量
            map.put("begin", fromMinDate(date));
            Integer newCount = userMapper.countByTime(map); //每天新增用户数量
            newUserList.add(newCount == null ? 0 : newCount);
            totalUserList.add(totalCount == null ? 0 : totalCount);
        }
        //返回数据
        return UserReportVO.builder().dateList(StringUtils.join(dateList, ",")).newUserList(StringUtils.join(newUserList, ",")).totalUserList(StringUtils.join(totalUserList, ",")).build();
    }

    /**
     * 查询销量排名top10接口
     *
     * @param begin 开始时间
     * @param end   结束时间
     * @return vo
     */
    @Override
    public SalesTop10ReportVO getTop10(LocalDate begin, LocalDate end) {
        List<GoodsSalesDTO> salesTop10 = orderMapper.getSalesTop10(fromMinDate(begin), fromMaxDate(end));
        List<String> nameList = null;
        List<Integer> numberList = null;
        if (salesTop10 != null && !salesTop10.isEmpty()) {
            nameList = salesTop10.stream().map(GoodsSalesDTO::getName).toList();//名称列表
            numberList = salesTop10.stream().map(GoodsSalesDTO::getNumber).toList();//销量列表
        }
        //封装数据返回
        return SalesTop10ReportVO.builder().nameList(StringUtils.join(nameList, ",")).numberList(StringUtils.join(numberList, ",")).build();
    }

    /**
     * 导出运营数据报表
     *
     * @param response HttpServletResponse
     */
    @Override
    public void exportBusinessData(HttpServletResponse response) {
        //1.查询数据库，获取营业数据----查询最近30天的运营数据
        LocalDate beginTime = LocalDate.now().minusDays(30);//往后倒30天
        LocalDate endTime = LocalDate.now().minusDays(1);//往后倒一天
        BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(beginTime, LocalTime.MIN), LocalDateTime.of(endTime, LocalTime.MAX));
        //2.通过pol写入Excel文件
        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        if (in != null) {
            //基于模板文件创建一个Excel文件
            try {
                XSSFWorkbook excel = new XSSFWorkbook(in);
                XSSFSheet sheet = excel.getSheet("Sheet1");

                //获取第二行 index为1 从0 开始
                //获取第二个单元格 index为1 从0 开始
                //填充数据 ---时间
                sheet.getRow(1).getCell(1).setCellValue("时间:" + beginTime + "到" + endTime);
                //获得第四行
                XSSFRow row = sheet.getRow(3);
                //营业额
                row.getCell(2).setCellValue(businessData.getTurnover());
                //订单完成率
                row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                //新增用户数
                row.getCell(6).setCellValue(businessData.getNewUsers());
                //获得第5行
                row = sheet.getRow(4);
                //新增有效订单
                row.getCell(2).setCellValue(businessData.getValidOrderCount());
                //平均客单价
                row.getCell(4).setCellValue(businessData.getUnitPrice());

                //填充明细数据
                for (int i = 0; i < 30; i++) {
                    LocalDate date = beginTime.plusDays(i);
                    //查询某一天的营业数据
                    BusinessDataVO data = workspaceService.getBusinessData(
                            LocalDateTime.of(date, LocalTime.MIN),
                            LocalDateTime.of(date, LocalTime.MAX));
                    //获得某一行
                    row = sheet.getRow(7 + i);
                    //日期
                    row.getCell(1).setCellValue(date.toString());
                    //营业额
                    row.getCell(2).setCellValue(data.getTurnover());
                    //新增有效订单
                    row.getCell(3).setCellValue(data.getValidOrderCount());
                    //订单完成率
                    row.getCell(4).setCellValue(data.getOrderCompletionRate());
                    //平均客单价
                    row.getCell(5).setCellValue(data.getUnitPrice());
                    //新增用户数
                    row.getCell(6).setCellValue(data.getNewUsers());
                }
                //3.通过输出流将Excel文件下载到客户端
                ServletOutputStream outputStream = response.getOutputStream();
                excel.write(outputStream);

                //关闭资源
                outputStream.close();
                excel.close();
                in.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }


    @Contract(value = "_ -> new", pure = true)
    private @NotNull LocalDateTime fromMinDate(LocalDate date) {
        return LocalDateTime.of(date, LocalTime.MIN);
    }

    @Contract(value = "_ -> new", pure = true)
    private @NotNull LocalDateTime fromMaxDate(LocalDate date) {
        return LocalDateTime.of(date, LocalTime.MAX);
    }


    private @NotNull List<LocalDate> generateDateList(LocalDate begin, LocalDate end) {
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        return dateList;
    }
}

